package cn.ctodb.mall.web.rest;

import com.codahale.metrics.annotation.Timed;
import cn.ctodb.mall.service.BackOrderService;
import cn.ctodb.mall.web.rest.util.HeaderUtil;
import cn.ctodb.mall.service.dto.BackOrderDTO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing BackOrder.
 */
@RestController
@RequestMapping("/api")
public class BackOrderResource {

    private final Logger log = LoggerFactory.getLogger(BackOrderResource.class);
        
    @Inject
    private BackOrderService backOrderService;

    /**
     * POST  /back-orders : Create a new backOrder.
     *
     * @param backOrderDTO the backOrderDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new backOrderDTO, or with status 400 (Bad Request) if the backOrder has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/back-orders")
    @Timed
    public ResponseEntity<BackOrderDTO> createBackOrder(@RequestBody BackOrderDTO backOrderDTO) throws URISyntaxException {
        log.debug("REST request to save BackOrder : {}", backOrderDTO);
        if (backOrderDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("backOrder", "idexists", "A new backOrder cannot already have an ID")).body(null);
        }
        BackOrderDTO result = backOrderService.save(backOrderDTO);
        return ResponseEntity.created(new URI("/api/back-orders/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("backOrder", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /back-orders : Updates an existing backOrder.
     *
     * @param backOrderDTO the backOrderDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated backOrderDTO,
     * or with status 400 (Bad Request) if the backOrderDTO is not valid,
     * or with status 500 (Internal Server Error) if the backOrderDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/back-orders")
    @Timed
    public ResponseEntity<BackOrderDTO> updateBackOrder(@RequestBody BackOrderDTO backOrderDTO) throws URISyntaxException {
        log.debug("REST request to update BackOrder : {}", backOrderDTO);
        if (backOrderDTO.getId() == null) {
            return createBackOrder(backOrderDTO);
        }
        BackOrderDTO result = backOrderService.save(backOrderDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("backOrder", backOrderDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /back-orders : get all the backOrders.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of backOrders in body
     */
    @GetMapping("/back-orders")
    @Timed
    public List<BackOrderDTO> getAllBackOrders() {
        log.debug("REST request to get all BackOrders");
        return backOrderService.findAll();
    }

    /**
     * GET  /back-orders/:id : get the "id" backOrder.
     *
     * @param id the id of the backOrderDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the backOrderDTO, or with status 404 (Not Found)
     */
    @GetMapping("/back-orders/{id}")
    @Timed
    public ResponseEntity<BackOrderDTO> getBackOrder(@PathVariable Long id) {
        log.debug("REST request to get BackOrder : {}", id);
        BackOrderDTO backOrderDTO = backOrderService.findOne(id);
        return Optional.ofNullable(backOrderDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /back-orders/:id : delete the "id" backOrder.
     *
     * @param id the id of the backOrderDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/back-orders/{id}")
    @Timed
    public ResponseEntity<Void> deleteBackOrder(@PathVariable Long id) {
        log.debug("REST request to delete BackOrder : {}", id);
        backOrderService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("backOrder", id.toString())).build();
    }

    /**
     * SEARCH  /_search/back-orders?query=:query : search for the backOrder corresponding
     * to the query.
     *
     * @param query the query of the backOrder search 
     * @return the result of the search
     */
    @GetMapping("/_search/back-orders")
    @Timed
    public List<BackOrderDTO> searchBackOrders(@RequestParam String query) {
        log.debug("REST request to search BackOrders for query {}", query);
        return backOrderService.search(query);
    }


}
